golang 反射构造map

导入reflect 包

import (
	"reflect"
)

获取map的类型:

t := reflect.TypeOf(input)
log.Printf("%s",t)

通过获取的type构造Map:

res := reflect.MakeMap(t)

reflect.Value 转换成接口:

inter:= res.Interface()

示例: reflect_map.go

package main

import (
	"reflect"
)

func main() {
	imap := make(map[string]string)
	var input interface{}
	input = imap
	m := reflect.ValueOf(input)
	if m.Kind() == reflect.Map {
		res := reflect.MakeMap(m.Type())
		keys := m.MapKeys()
		for _, k := range keys {
			key := k.Convert(res.Type().Key()) //.Convert(m.Type().Key())
			value := m.MapIndex(key)
			res.SetMapIndex(key, value)
		}
	}
}
humboldt Written by:

humboldt 的趣味程序园